﻿
//#region NewsCategory

function CreateDropDownList(data) {
    var strOption = "<option value='0'>请选择...</option>";
    for (var i = 0; i < data.length; i++) {
        strOption += "<option value='" + data[i].CategoryCode + "'>" + data[i].CategoryName + "</option>";
    }

    return strOption;
}

function ListNewsCategory() {
    if (type == "ImageCategory" || type == "Image")
        url = 'NewsWebService.asmx/ListImageCategory';
    else
        url = 'NewsWebService.asmx/ListNewsCategory';
    $.ajax({
        type: 'POST',
        contentType: 'application/json;',
        url: url,
        data: '',
        dataType: 'json',
        success: function (ctx) {
            if (type == "News" || type == "Image") {
                var selectedValue = $("#ddlCategory  option:selected").val()
                if (selectedValue == "" || selectedValue == undefined || selectedValue == null) {
                    var strOption = CreateDropDownList(ctx.d);
                    $("#ddlCategory").append($(strOption));
                }
            }
            else {
                var trHtml = CreateCategoryTable(ctx.d);
                $("#tabelCategory").append($(trHtml));
            }
        },
        error: function (ctx) {
            ShowErrorMessage(ctx);
        }
    });
}

function CategoryChanged() {
    categoryCodeUI = $("#ddlCategory  option:selected").val();
    if (categoryCodeUI == '0') {
        $("#divPage").html('');
        categoryCodeUI = "0";
        return;
    }

    if (type == "News") {
        $("#tabelNews tbody").html('');
        ListNewsInfoByCategoryCode();
    }
    else {
        $("#tabImage").html('');
        ListImageInfoByCategoryCode();
    }
    $("#hiddenCategoryCode").val(categoryCodeUI);
    //categoryCodeUI = categoryCode;
}

function CreateCategoryTable(result) {
    var tableHTML = '';
    for (var i = 0; i < result.length; i++) {
        tableHTML += '<tr>';
        var dateTime = ChangeDateFormat(result[i].CreateDate);
        tableHTML += '<td><input type="checkbox" value="\'' + result[i].CategoryCode + '\'" /></td>';
        tableHTML += '<td>' + result[i].CategoryCode + '</td>';
        tableHTML += '<td>' + result[i].CategoryName + '</td>';
        tableHTML += '<td>' + result[i].CategoryDesc + '</td>';
        tableHTML += '<td>' + dateTime + '</td>';
        tableHTML += '<td><a href="#" rel="facebox" onclick="EditCategory(\'' + result[i].CategoryCode + '\')" title="Edit"><img src="resources/images/icons/pencil.png" alt="Edit" /></a> <a href="#" onclick="if(!window.confirm(\'是否确认删除?\')) return;DeleteCategory(\'' + result[i].CategoryCode + '\', \'single\');" title="Delete"><img src="resources/images/icons/cross.png" alt="Delete" /></a>';
        tableHTML += ' </tr>';
    }
    return tableHTML;
}

function AddCategory() {
    var urlService = "";
    if (type == "Category")
        urlService = $("#hiddenCategoryCode").val() != "" ? 'NewsWebService.asmx/UpdateNewsCategory' : 'NewsWebService.asmx/CreateNewsCategory';
    else
        urlService = $("#hiddenCategoryCode").val() != "" ? 'NewsWebService.asmx/UpdateImageCategory' : 'NewsWebService.asmx/CreateImageCategory';
    var options = {
        url: urlService,
        success: function (ctx) {
            $.facebox.close();
            RefreshCategoryList(type);
        },
        error: function (ctx) {
            ShowErrorMessage(ctx);
        }
    };

    $('#formAddCategory').ajaxForm(options);
}

function EditCategory(categoryCode) {
    var url = type == "ImageCategory" ? 'NewsWebService.asmx/GetImageCategory' : 'NewsWebService.asmx/GetCategory';
    var htmlPage = type == "ImageCategory" ? "AddImageCategory.html" : "AddCategory.html";
    $.ajax({
        type: 'POST',
        contentType: 'application/json;',
        url: url,
        data: '{"categoryCode":"' + categoryCode + '"}',
        dataType: 'json',
        success: function (ctx) {
            jQuery.facebox(function () {
                $.get(htmlPage, function (data) {
                    $.facebox(data);
                    $("#hiddenCategoryCode").val(ctx.d.CategoryCode);
                    $("#categoryName").val(ctx.d.CategoryName);
                    $("#categoryDesc").val(ctx.d.CategoryDesc);
                });
            })
        },
        error: function (ctx) {
            ShowErrorMessage(ctx);
        }
    });
}

function DeleteSeletedCategory(selectRecords) {
    selectRecords.each(function () {
        var categoryCode = $(this).val();
        if (categoryCode != "") {
            categoryCode = categoryCode.replace(/\'/g, "");
            DeleteCategory(categoryCode, "more");
        }
    });

    RefreshCategoryList();
}

function DeleteCategory(categoryCode, typeDelete) {
    var url = type == "ImageCategory" ? 'NewsWebService.asmx/DeleteImageCategory' : 'NewsWebService.asmx/DeleteNewsCategory';
    $.ajax({
        type: 'POST',
        contentType: 'application/json;',
        url: url,
        data: '{"categoryCode":"' + categoryCode + '"}',
        dataType: 'json',
        success: function (ctx) {
            CheckOperateSuccessed(ctx);
            if (typeDelete == "single") {
                RefreshCategoryList();
            }
        },
        error: function (ctx) {
            ShowErrorMessage(ctx);
        }
    });
}

function RefreshCategoryList() {
    $("#tabelCategory tbody").html('');
    ListNewsCategory();
}

//#endregion

//#region NewsInfo

//#region Operate

function AddNews() {
    var urlService;
    if ($("#hiddenNewsCode").val() != "") {
        urlService = 'NewsWebService.asmx/UpdateNewsInfo';
    }
    else {
        $("#hiddenCategoryCode").val(categoryCodeUI);
        urlService = 'NewsWebService.asmx/CreateNewsInfo';
    }
    $("#hiddenNewContent").val(editor.html());

    var options = {
        url: urlService,
        success: function (ctx) {
            $.facebox.close();
            ListNewsInfoByCategoryCode(currentIndex);
        },
        error: function (ctx) {
            ShowErrorMessage(ctx);
        }
    };

    $('#formAdd').ajaxForm(options);
}

function EditNewsInfo(newsCode) {
    $.ajax({
        type: 'POST',
        contentType: 'application/json;',
        url: 'NewsWebService.asmx/GetNewsInfo',
        data: '{"newsCode":"' + newsCode + '"}',
        dataType: 'json',
        success: function (ctx) {
            jQuery.facebox(function () {
                $.get('addnews.html', function (data) {
                    $.facebox(data);
                    $("#hiddenCategoryCode").val(ctx.d.CategoryCode);
                    $("#hiddenNewsCode").val(ctx.d.NewsCode);
                    $("#newsName").val(ctx.d.NewsName);
                    $("#newsDesc").val(ctx.d.NewsDesc);
                    editor.html(ctx.d.NewsContent);
                });
            })
        },
        error: function (ctx) {
            ShowErrorMessage(ctx);
        }
    });
}

function DeleteNewsInfo(newsCode) {
    $.ajax({
        type: 'POST',
        contentType: 'application/json;',
        url: 'NewsWebService.asmx/DeleteNewsInfo',
        data: '{"newsCode":"' + newsCode + '"}',
        dataType: 'json',
        success: function (ctx) {
            ListNewsInfoByCategoryCode(currentIndex);
        },
        error: function (ctx) {
            ShowErrorMessage(ctx);
        }
    });
}

function DeleteSeletedNews() {
    var countDelete = 0;
    $("input[type=checkbox]:checked").each(function () {
        if ($(this).val() != "" && $(this).val() != "all") {
            countDelete++;
            var newsCode = $(this).val().replace(/\'/g, "");
            $.ajax({
                type: 'POST',
                contentType: 'application/json;',
                url: 'NewsWebService.asmx/DeleteNewsInfo',
                data: '{"newsCode":"' + newsCode + '"}',
                dataType: 'json',
                success: function (ctx) {
                    var result = eval(ctx);
                },
                error: function (ctx) {
                    ShowErrorMessage(ctx);
                }
            });
        }
    });

    if (countDelete > 0)
        ListNewsInfoByCategoryCode(currentIndex);
}

//#endregion

//#region Get data

function CreateTable(result) {
    var tableHTML = '';
    for (var i = 0; i < result.length; i++) {
        tableHTML += '<tr>';
        var dateTime = ChangeDateFormat(result[i].CreateDate);
        tableHTML += '<td><input type="checkbox" value="\'' + result[i].NewsCode + '\'" /></td>';
        tableHTML += '<td>' + result[i].NewsCode + '</td>';
        tableHTML += '<td>' + result[i].NewsName + '</td>';
        tableHTML += '<td>' + result[i].NewsDesc + '</td>';
        tableHTML += '<td>' + result[i].Creator + '</td>';
        tableHTML += '<td>' + dateTime + '</td>';
        tableHTML += '<td><a href="#" rel="facebox" onclick="EditNewsInfo(\'' + result[i].NewsCode + '\')" title="Edit"><img src="resources/images/icons/pencil.png" alt="Edit" /></a> <a href="#" onclick="if(!window.confirm(\'是否确认删除?\')) return;DeleteNewsInfo(\'' + result[i].NewsCode + '\');" title="Delete"><img src="resources/images/icons/cross.png" alt="Delete" /></a>';
        tableHTML += ' </tr>';
    }
    return tableHTML;
}

function ListNewsInfoByCategoryCode(index) {
    $("#tabelNews tbody").html('');
    var categoryCode = $("#ddlCategory  option:selected").val();
    if (index == undefined || index == null)
        index = 1;
    var startIndex = index - 1;
    $.ajax({
        type: 'POST',
        contentType: 'application/json;',
        url: 'NewsWebService.asmx/ListNewsInfo',
        data: '{"categoryCode":"' + categoryCode + '", "startIndex":"' + startIndex + '", "limit": 10}',
        dataType: 'json',
        success: function (ctx) {
            var result = eval('(' + ctx.d + ')');
            var trHtml = CreateTable(result.data);
            $("#tabelNews").append($(trHtml))
            var htmlPage = CreatePagination(result, index, "ListNewsInfoByCategoryCode");
            $("#divPage").html(htmlPage);
        },
        error: function (ctx) {
            ShowErrorMessage(ctx);
        }
    });
}

//#endregion

//#endregion

//#region ImageCategory

//#endregion

//#region ImageInfo

function AddImage() {
    var urlService;
    if ($("#hiddenImageCode").val() != "") {
        urlService = 'NewsWebService.asmx/UpdateImageInfo';
    }
    else {
        $("#hiddenCategoryCode").val(categoryCodeUI);
        urlService = 'NewsWebService.asmx/CreateImageInfo';
    }

    var options = {
        url: urlService,
        success: function (ctx) {
            if (CheckOperateSuccessedForAdd(ctx)) {
                $.facebox.close();
                ListImageInfoByCategoryCode(currentIndex);
            }
        },
        error: function (ctx) {
            ShowErrorMessage(ctx);
        }
    };

    $('#formAddImage').ajaxForm(options);
}

function ListImageInfoByCategoryCode(index) {
    $.facebox.loading(true);
    $("#tabImage").html('');
    $("#divPage").html('');
    var categoryCode = $("#ddlCategory  option:selected").val();
    //var categoryCode = "C000000001";
    if (index == undefined || index == null)
        index = 1;
    var startIndex = index - 1;
    $.ajax({
        type: 'POST',
        contentType: 'application/json;',
        url: 'NewsWebService.asmx/ListImageInfo',
        data: '{"categoryCode":"' + categoryCode + '", "startIndex":"' + startIndex + '", "limit": 9}',
        dataType: 'json',
        success: function (ctx) {
            var result = eval('(' + ctx.d + ')');
            var trHtml = CreateImageList(result.data);
            $("#tabImage").append($(trHtml))
            var htmlPage = CreatePagination(result, index, "ListImageInfoByCategoryCode");
            $("#divPage").html(htmlPage);
            //if (countChanged == 0) 
            LoadJSForImage();
        },
        error: function (ctx) {
            ShowErrorMessage(ctx);
        }
    });
}

function CreateImageList(result) {

    var listHTML = '<ul class="portfolio_items">';
    
    for (var i = 0; i < result.length; i++) {
        var id = "id-" + (i + 1);
        listHTML += '<li class="left13 illustrations" data-id="' + id + '">';
        listHTML += '<h3>' + result[i].ImageName + '</h3>';
        listHTML += '<div class="ts-display-pf-img">';
        listHTML += '<a href="' + result[i].FilePath + '" rel="prettyPhoto[gallery]"><span class="rollover"></span><img src="' + result[i].ThumbnailPath + '" style="padding:4px;border:solid 1px #ececec;display:block;width:270px;height:142px;" alt="" border="0" /></a>';
    }

    listHTML += "</ul>";

    return listHTML;
}

//#endregion

//#region Common method

function LoadJSForImage() {
    var headHtml = $("#headImage").html();
    var bodyHtml = $("#tab1").html();
    $("#headImage").html('');
    $("#bodyHtml").html('');
    $("#headImage").html(headHtml);
    $("#bodyHtml").html(bodyHtml);
    $.facebox.close();
}

function CheckOperateSuccessed(ctx) {
    var result = eval('(' + ctx.d + ')');
    if (!result.success) {
        alert(result.errors.clientCode);
        return false;
    }

    return true;
}

function CheckOperateSuccessedForAdd(ctx) {
    var result = eval('(' + ctx.text + ')');
    alert(result);
    if (!result.success) {
        alert(result.errors.clientCode);
        return false;
    }

    return true;
}

function ShowAddWindow(type, ctrl, htmlPage) {
    if (type == "News" || type == "Image") {
        if (categoryCodeUI == undefined || categoryCodeUI == null || categoryCodeUI == "0") {
            alert("请选择分类");
            return;
        }
    }

    ctrl.attr("rel", "facebox");

    jQuery.facebox(function () {
        $.get(htmlPage, function (data) {
            $.facebox(data);
        });
    })
}

function CheckSelectedItems(checkboxs) {
    if (checkboxs.length == 0) {
        alert("请选择需要删除的记录!");
        return false;
    }

    if (!window.confirm('是否确认删除?')) {
        return false;
    }

    return true;
}

function ShowErrorMessage(data) {
    var err = eval('(' + data.responseText + ')');
    alert(err.Message);
}

function utcToDate(utcCurrTime) {
    utcCurrTime = utcCurrTime + "";
    var date = "";
    var month = new Array();
    month["Jan"] = 1;
    month["Feb"] = 2;
    month["Mar"] = 3;
    month["Apr"] = 4;
    month["May"] = 5;
    month["Jun"] = 6;
    month["Jul"] = 7;
    month["Aug"] = 8;
    month["Sep"] = 9;
    month["Oct"] = 10;
    month["Nov"] = 11;
    month["Dec"] = 12;
    var week = new Array();
    week["Mon"] = "一";
    week["Tue"] = "二";
    week["Wed"] = "三";
    week["Thu"] = "四";
    week["Fri"] = "五";
    week["Sat"] = "六";
    week["Sun"] = "日";

    str = utcCurrTime.split(" ");
    date = str[5] + "-";
    date = date + month[str[1]] + "-" + str[2] + "-" + str[3];
    return date;
}

function ChangeDateFormat(val) {
    if (val != null) {
        var date = new Date(parseInt(val.replace("/Date(", "").replace(")/", ""), 10));
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        return date.getFullYear() + "-" + month + "-" + currentDate + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    }

    return "";
}

function FaceboxClose() {
    $.facebox.close();
}

function CreatePagination(result, pageIndex, functionName) {
    var pageHtml = '';
    var pageCount = result.total / 10;
    var count = 0;
    var index = pageIndex;
    var perv = pageIndex - 1;
    var next = pageIndex + 1;
    var pageCountInt = parseInt(pageCount);
    if (pageCountInt != pageCount) {
        pageCountInt++;
    }
    if (pageCountInt <= 5)
        index = 1;

    if (pageCountInt == 1)
        return pageHtml;

    if (pageIndex > 1)
        pageHtml += '<a href="#" title="" onclick = "' + functionName + '(' + perv + ')" class="number">上一页</a>';

    for (var i = index; i <= pageCountInt; i++) {
        count++;
        if (i - 1 > 2 && count == 1) {
            pageHtml += '<a href="#" title="" onclick = "' + functionName + '(1)" title="" class="number">1</a>';
            pageHtml += '<span>...</span>';
        }
        if (i - 1 > 0 && count == 1 && index - 1 < 3) {
            for (var j = 1; j < index; j++) {
                pageHtml += '<a href="#" title="" onclick = "' + functionName + '(' + j + ')" class="number">' + j + '</a>';
            }
        }

        if (i == pageIndex) {
            pageHtml += '<a href="#" title="" onclick = "' + functionName + '(' + i + ')" class="number current">' + i + '</a>';
            currentIndex = i;
        }
        else {
            pageHtml += '<a href="#" title="" onclick = "' + functionName + '(' + i + ')" title="" class="number">' + i + '</a>';
        }

        if (count > 5 && pageCountInt - i > 1) {
            pageHtml += '<span>...</span>';
            pageHtml += '<a href="#" onclick = "' + functionName + '(' + pageCountInt + ')" title="" class="number">' + pageCountInt + '</a>';
            break;
        }
    }

    if (pageIndex + 1 <= pageCountInt)
        pageHtml += '<a href="#" onclick = "' + functionName + '(' + next + ')" title="" class="number">下一页</a>'

    return pageHtml;
}

//#endregion



